// merge3.hxx


#ifndef _BLOGS_MERGE3
#define _BLOGS_MERGE3


#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"
#include "std_out.hxx"


namespace blogs
{


class Merge3
{

  private:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __exch__(Array<_T> & a, int i, int j)
    {
        _T t = a[i];
        a[i] = a[j];
        a[j] = t;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __merge__(Array<_T> & a, int lo, int mi, int hi, Array<_T> & aux)
    {
        int i = lo, j = mi+1;
        for (int k = lo; k <= hi; ++k)
            if      (i > mi)                aux[k] = a[j++];
            else if (j > hi)                aux[k] = a[i++];
            else if (__less__(a[j], a[i]))  aux[k] = a[j++];
            else                            aux[k] = a[i++];
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __sort__(Array<_T> & a, int lo, int hi, Array<_T> & aux)
    {
        if (hi - lo <= 15) {
            for (int i = lo+1; i <= hi; ++i)
                for (int j = i; j > lo && __less__(aux[j], aux[j-1]); --j)
                    __exch__(aux, j, j-1);
        } else {
            int mi = lo + (hi - lo) / 2;
            __sort__(aux, lo, mi, a);
            __sort__(aux, mi+1, hi, a);
            if (__less__(a[mi], a[mi+1]))
                for (int i = lo; i <= hi; ++i)
                    aux[i] = a[i];
            else
                __merge__(a, lo, mi, hi, aux);
        }
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(Array<_T> & a)
    {
        int N = a.size();
        Array<_T> aux = Array<_T>(N);
        for (int k = 0; k < N; ++k)
            aux[k] = a[k];
        __sort__(aux, 0, N-1, a);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }

};


} // end of namespace blogs


#endif

